/*
 * @lc app=leetcode.cn id=21 lang=javascript
 *
 * [21] 合并两个有序链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeTwoLists = function(list1, list2) {
    function listToArr(list, totalArr = []) {
        if (!list) {
            return totalArr
        }
        totalArr.push(list.val)
        if (list.next) {
            return listToArr(list.next, totalArr)
        } else {
            return totalArr
        }
    }
    function arrToList(arr, totalList = new ListNode()) {
            if (arr.length !== 0) {
                totalList.val = arr.pop()
                
                arr.length === 0 ? totalList.next = null : totalList.next = new ListNode()
                totalList.next = arrToList(arr, totalList.next)
            }
            return totalList
    }
    let arr1 = listToArr(list1), arr2 = listToArr(list2)
    let arr = arr1.concat(arr2)
    if (arr.length === 0) {
        return list1
    }
    arr.sort((a, b) => b - a)
    return arrToList(arr)
};
// @lc code=end

// todo 这题不应该用数组的解法，应该直接操作定义的ListNode

// function ListNode(val, next) {
//     this.val = (val===undefined ? 0 : val)
//     this.next = (next===undefined ? null : next)
// }

// list1 = new ListNode(1, new ListNode(2, new ListNode(4)))
// list2 = new ListNode(1, new ListNode(3, new ListNode(4)))

// const res = mergeTwoLists(list1, list2)

// console.log(res)


